﻿// Copyright (c) Microsoft Corporation and Contributors.
// Licensed under the MIT License.
using SDKTemplate;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Runtime.InteropServices;
using System.Threading;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace FASTControlUI
{
    /// <summary>
    /// An empty window that can be used on its own or navigated to within a Frame.
    /// </summary>
    class WindowsSystemDispatcherQueueHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        struct DispatcherQueueOptions
        {
            internal int dwSize;
            internal int threadType;
            internal int apartmentType;
        }

        [DllImport("CoreMessaging.dll")]
        private static extern int CreateDispatcherQueueController([In] DispatcherQueueOptions options, [In, Out, MarshalAs(UnmanagedType.IUnknown)] ref object dispatcherQueueController);

        object m_dispatcherQueueController = null;
        public void EnsureWindowsSystemDispatcherQueueController()
        {
            if (Windows.System.DispatcherQueue.GetForCurrentThread() != null)
            {
                // one already exists, so we'll just use it.
                return;
            }

            if (m_dispatcherQueueController == null)
            {
                DispatcherQueueOptions options;
                options.dwSize = Marshal.SizeOf(typeof(DispatcherQueueOptions));
                options.threadType = 2;    // DQTYPE_THREAD_CURRENT
                options.apartmentType = 2; // DQTAT_COM_STA

                CreateDispatcherQueueController(options, ref m_dispatcherQueueController);
            }
        }
    }

    public sealed partial class MainWindow : Window
    {
        static public new MainWindow Current;
        private MainConfig mainConfig;
        Timer timer;
        public MainWindow()
        {
            this.InitializeComponent();
            this.ExtendsContentIntoTitleBar = true;
            this.SetTitleBar(AppTitleBar);
            this.Title = "FAST控制中心";
            Current = this;
            this.Activated += Window_Activated;
            this.Closed += Window_Closed;
            ((FrameworkElement)this.Content).ActualThemeChanged += Window_ThemeChanged;
            mainConfig = MainConfig.GetMainConfig(this);
            mainConfig.ReadConfig();
            GameDataPublic.Load();
            WindowHelper.TrackWindow(this);
            timer = new Timer(args => { CloseNotify(); }, null, 1000, Timeout.Infinite);
        }
        public void SetTitleBarWhith(int width)
        {
            AppTitleBar.Width = width;
        }
        private void nvSample_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
        {
            if (args.IsSettingsSelected)
            {
                contentFrame.Navigate(typeof(SettingPage));
            }
            else
            {
                var selectedItem = (NavigationViewItem)args.SelectedItem;
                if (selectedItem != null)
                {
                    string selectedItemTag = ((string)selectedItem.Tag);
                    if (selectedItemTag != "WheelPage")
                    {
                        MainWindow.Current.SetTitleBarWhith((int)contentFrame.ActualWidth);
                    }
                    else
                    {
                        MainWindow.Current.SetTitleBarWhith(200);
                    }
                    string pageName = "FASTControlUI." + selectedItemTag;
                    Type pageType = Type.GetType(pageName);
                    contentFrame.Navigate(pageType);
                }
            }
        }

        private void nvSample_Loaded(object sender, RoutedEventArgs e)
        {
            //contentFrame.Navigate(Type.GetType("FASTControlUI.HomePage"));
        }
        private void Window_Activated(object sender, WindowActivatedEventArgs args)
        {
            //mainConfig.HomeStyle.IsInputActive = args.WindowActivationState != WindowActivationState.Deactivated;
        }

        public void NotifyUser(string strMessage, NotifyType type)
        {
            // If called from the UI thread, then update immediately.
            // Otherwise, schedule a task on the UI thread to perform the update.
            this.invoke(() => { UpdateStatus(strMessage, type); });
        }
        private void invoke(Action action, Microsoft.UI.Dispatching.DispatcherQueuePriority priority = Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal)
        {
            this.DispatcherQueue.TryEnqueue(priority, () =>
            {
                action();
            });
        }
        private void CloseNotify()
        {
            invoke(() => { infoBar.IsOpen = false; });
        }
        private void UpdateStatus(string strMessage, NotifyType type)
        {
            switch (type)
            {
                case NotifyType.StatusMessage:
                    infoBar.Severity = InfoBarSeverity.Informational;
                    break;
                case NotifyType.ErrorMessage:
                    infoBar.Severity = InfoBarSeverity.Error;
                    break;
            }
            infoBar.Message = strMessage;
            infoBar.IsOpen = true;
            timer.Change(1000, Timeout.Infinite);
        }
        private void Window_Closed(object sender, WindowEventArgs args)
        {
            // Make sure any Mica/Acrylic controller is disposed
            // so it doesn't try to use this closed window.
            mainConfig.SaveConfig();

            GameDataPublic.Save();
            this.Activated -= Window_Activated;
        }

        private void Window_ThemeChanged(FrameworkElement sender, object args)
        {
            mainConfig.HomeStyle.SetConfigurationSourceTheme(((FrameworkElement)this.Content).ActualTheme);
        }

    }

}

